import { Drawer, Button } from 'antd';
import React, { useReducer } from 'react';

const useDrawer = (defaultProps) => {
  const [state, dispatch] = useReducer((state, action) => ({ ...state, ...action }), {
    open: false,
    props: {},
  });

  function open(props) {
    dispatch({ open: true, props: { width: 'auto', ...defaultProps, ...props } });
    return { destroy };
  }

  function destroy() {
    dispatch({ open: false });
  }

  function Slot() {
    const { onOk, content, ...rest } = state.props;
    return (
      <Drawer onClose={destroy} extra={(<Button type='primary' onClick={async () => {
        if (!onOk) return destroy();
        try {
          const ok = await onOk();
          if (ok !== false) destroy();
        } catch (e) { }
      }}>确定</Button>)} {...rest} open={state.open}>
        {content}
      </Drawer>
    );
  }

  return [{ open }, <Slot />];
};

export default useDrawer;